package com.zhs.elasticsearch.thread;

import cn.hutool.core.util.IdUtil;
import com.zhs.elasticsearch.match.eo.UserEO;
import com.zhs.elasticsearch.match.esRepository.UserRepository;
import com.zhs.elasticsearch.util.CityUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 *
 * @Author zhenghuisheng
 * @Date：2025/6/23 16:21
 */
@Slf4j
public class UserSaveTask implements Runnable {

    private final UserRepository userRepository;

    public UserSaveTask(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 批量插入10 0000条数据
     */
    @Override
    public void run() {
        List<UserEO> list = new ArrayList<>();
        //每次1000条
        log.info("开始插入数据...");
        for (int i = 0; i < 100; i++) {
            list.add(buildUserBaseInfo());
        }
        userRepository.saveAll(list);
        log.info("结束插入数据...");
    }

    /**
     * 构建用户基础信息
     * @return
     */
    public UserEO buildUserBaseInfo() {
        UserEO user = new UserEO();

        //设置用户id,雪花算法
        user.setId(IdUtil.getSnowflakeNextId());
        user.setNickName("用户" + getRandomString(6));
        //设置性别
        user.setSex(ThreadLocalRandom.current().nextInt(0, 2));
        //构建年月日
        int year = randBetween(1990, 2010);
        int month = randBetween(1, 12);
        int day = getRandomDay(year, month);
        user.setBirthYear(year);
        user.setBirthMonth(month);
        user.setBirthDay(day);

        //设置身高体重
        user.setHeight(randBetween(165, 185));
        user.setWeight(randBetween(120, 160));
        user.setEduLevel(randBetween(3, 7)); // 大专以下 ~ 硕士

        //居住省份+城市
        String[] live = CityUtil.getRandomCity();
        user.setLiveProvince(live[0]);
        user.setLiveCity(live[1]);

        //老家省份+城市
        String[] reg = CityUtil.getRandomCity();
        user.setRegProvince(reg[0]);
        user.setRegCity(reg[1]);

        // 默认不被删除
        user.setDelFlag(0);
        return user;
    }

    private static String getRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder(length);
        ThreadLocalRandom r = ThreadLocalRandom.current();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(r.nextInt(chars.length())));
        }
        return sb.toString();
    }

    private static int randBetween(int start, int end) {
        return ThreadLocalRandom.current().nextInt(start, end + 1);
    }

    private static int getRandomDay(int year, int month) {
        // 获取当月最大天数
        return randBetween(1, LocalDate.of(year, month, 1).lengthOfMonth());
    }
}
